'''
Author: 洛白 luogoddes@qq.com
Date: 2024-09-29 21:14:02
LastEditors: 洛白 luogoddes@qq.com
LastEditTime: 2024-10-03 00:23:14
Description: 
'''
from flask import Flask, request, send_file, jsonify ,send_from_directory
from flask_cors import CORS
from docx import Document
from io import BytesIO
import os
import win32com.client as win32
import pythoncom  # 添加这行导入
import webbrowser
from threading import Timer

app = Flask(__name__,
            static_folder='dist',
            static_url_path='')  # 将 dist 作为静态文件夹
CORS(app, resources={r"/*": {"origins": "http://localhost:3000"}})

@app.route('/merge', methods=['POST'])
def test():
    print("================")
    try:
        pythoncom.CoInitialize()  # 初始化 COM 库
        files = request.files.getlist('files')
        if not files:
            return jsonify({'error': 'No files uploaded'}), 400

        #print(files)

        # 启动 Word 应用
        word = win32.gencache.EnsureDispatch('Word.Application')
        word.Visible = False

        # 新建合并后的文档
        output = word.Documents.Add()

        # 使用内存中的 BytesIO 来保存文件
        for file in files:
            # 将文件内容写入 BytesIO 对象
            file_stream = BytesIO(file.read())

            # 创建一个临时文件来保存每个上传的文档内容
            # Word COM 需要文件路径才能插入文件，这里使用 'InsertFile'
            temp_file_path = os.path.join(os.getcwd(), file.filename)
            with open(temp_file_path, 'wb') as temp_file:
                temp_file.write(file_stream.getbuffer())

            # 插入文件
            output.Application.Selection.InsertFile(temp_file_path)
            
            # 插入分页符
            output.Application.Selection.InsertBreak(win32.constants.wdPageBreak)

            # 删除临时文件
            os.remove(temp_file_path)

        # 创建 BytesIO 来保存合并后的文档
        merged_output = BytesIO()

        # 保存合并后的文档到内存中
        temp_merged_file = os.path.join(os.getcwd(), 'merged_document.docx')
        output.SaveAs(temp_merged_file)
        output.Close()

        # 将合并后的文件读取到内存
        with open(temp_merged_file, 'rb') as f:
            merged_output.write(f.read())

        merged_output.seek(0)

        # 删除本地合并文档文件
        os.remove(temp_merged_file)

        return send_file(merged_output, as_attachment=True, download_name='merged_document.docx', mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'), 200

    except Exception as e:
        print('Error in merge_documents:', e)
        return jsonify({'error': str(e)}), 500
    finally:
        pythoncom.CoUninitialize()  # 释放 COM 库


# 定义一个路由来展示 dist 文件夹下的 index.html
@app.route('/')
def serve_index():
    # 假设 dist 文件夹位于当前文件夹下
    return send_from_directory('dist', 'index.html')

# 启动 Flask 服务后自动打开浏览器访问 http://localhost:3000
def open_browser():
    webbrowser.open_new('http://localhost:3000')

if __name__ == '__main__':
    # 使用线程来延迟执行浏览器打开，确保 Flask 服务已经启动
    Timer(1, open_browser).start()
    # 启动 Flask 应用
    app.run(debug=True, port=3000)